import logging

from sqlalchemy import text

from comm.dbConnect import get_yun_session


def chartDbJonOne(sql,dbpool,parm=None):

    session = get_yun_session(dbpool = dbpool)
    try:
        rest = session.execute(text(sql), parm)
    except Exception as e:
        session.close()
        logging.info('语句执行失败1' + repr(e) + '语句' + sql + '参数' + str(parm))
        return None, repr(e)

    # 游标对象的description属性得到由字段和其他值组成的元组，格式：((字段1，...),(字段2，...)...)
    # 通过列表推导式，遍历元组，取遍历后的元组的第一个索引的值组成一个有字段组成的列表
    field_li = [k[0] for k in rest.cursor.description]
    # 所有数据
    try:
        data = rest.fetchone()
    except Exception as e:
        session.close()
        logging.info('语句执行失败2' + repr(e) + '语句' + sql + '参数' + str(parm))
        return None, repr(e)

    if data is None:
        logging.info('单个没有查询到数据')
        return None, None
    result = dict(zip(field_li, data))
    return result, None


def chartDbListJon(sql,dbpool,parm=None):
    session = get_yun_session(dbpool=dbpool)
    try:
        rest = session.execute(text(sql),parm)
    except Exception as e:
        session.close()
        logging.info('语句执行失败' + repr(e) + '语句' + sql + '参数' + str(parm))
        return [],repr(e)

    # 游标对象的description属性得到由字段和其他值组成的元组，格式：((字段1，...),(字段2，...)...)
    # 通过列表推导式，遍历元组，取遍历后的元组的第一个索引的值组成一个有字段组成的列表
    field_li = [k[0].lower() for k in rest.cursor.description]
    # 所有数据
    try:
        data_all = rest.fetchall()  # 查询所有数据，fetchall()或fetchone()要放到description后面，否则会报错
    except Exception as e:
        session.close()
        logging.info('语句执行失败' + repr(e) + '语句' + sql + '参数' + str(parm))
        return [],repr(e)

    if data_all is None:
        logging.info('列表None值未知错误')
        return [], 'None值未知错误'
    if len(data_all)==0:
        logging.info('列表没有查询到数据')
        return [],'没有查询到数据'
    result_list = list()
    for data in data_all:
        result = dict(zip(field_li, data))
        result_list.append(result)
    return result_list,None